package up7.utils;

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;

import net.sf.json.JSONObject;
import up7.XDebug;
import up7.sql.DataBaseType;

public class ConfigReader {
	public JSONObject m_files;
	public PathTool m_pt;
	public ReadContext m_jp;
	
	public ConfigReader()
	{
		this.m_pt = new PathTool();
		//自动加载/config.json
		String path = this.m_pt.MapPath("/config/config.json");
		String json = FileTool.readAll(path);		
		this.m_files = JSONObject.fromObject(json);
		this.m_jp = JsonPath.parse(json);
	}

	public static DataBaseType dbType(){
		ConfigReader r = new ConfigReader();
		String t = r.readString("database.connection.type");

		if(t.compareToIgnoreCase("mysql") ==0) return DataBaseType.MySQL;
		else if(t.compareToIgnoreCase("oracle") ==0) return DataBaseType.Oracle;
		else if(t.compareToIgnoreCase("sql") ==0) return DataBaseType.SqlServer;
		else if(t.compareToIgnoreCase("dmdb") ==0) return DataBaseType.DMDB;
		else if(t.compareToIgnoreCase("kingbase") ==0) return DataBaseType.KingBase;
		else if(t.compareToIgnoreCase("mongodb") ==0) return DataBaseType.MongoDB;
		return DataBaseType.SqlServer;
	}
	
	/**
	 * 将配置加载成一个json对象
	 * @param name
	 * @return
	 */
	public JSONObject module(String name)
	{
		String path = this.m_jp.read(name);
		XDebug.Output(path);
		path = this.m_pt.MapPath(path);
		String data = FileTool.readAll(path);
		return JSONObject.fromObject(data);
	}
	
	public JSONObject read(String name)
	{
		Object o = this.m_jp.read(name);
		return JSONObject.fromObject(o);
	}
	
	public String readString(String name)
	{
        Object o = this.m_jp.read(name);
        return o.toString();
	}

	/**
	 * 以jsonpath方式读取config.json中的bool值
	 * @param name
	 * @return
	 */
	public boolean readBool(String name)
	{
		Object o = this.m_jp.read(name);
		return Boolean.parseBoolean(o.toString());
	}

	/**
	 * 传输加密
	 * 配置：/config.json/security.encrypt
	 * @return
	 */
	public static boolean postEncrypt() {
		ConfigReader cr = new ConfigReader();
		return cr.readBool("security.encrypt");
	}

	public static boolean securityToken() {
		ConfigReader cr = new ConfigReader();
		return cr.readBool("security.token");
	}

	/**
	 * 存储加密
	 * @return
	 */
	public static boolean storageEncrypt(){
		ConfigReader cr = new ConfigReader();
		return cr.readBool("Storage.encrypt");
	}
}